<?php
/**
 * 定义f:checkboxes控件
 * 
 * 包含一组f:checkbox控件，使得可以整体对它们进行初始化和验证
 * 
 * 它能使用UIFormElement所具有的属性，除此之外还能使用：
 * - values <array> 一组checkbox的值
 * - labels <array> 一组checkbox的标签
 * - selected.values <array> 选中的值
 * - selected.list <string> 选中的值，以逗号相连
 * - options <array> 一组值和标签的关联数组 
 * - separator <string> checkbox之间的分隔符
 *
 * @package if
 * @subpackage module.ui
 * @since 1.1.0
 */
class UIFormCheckboxes extends UIFormElement {
	protected $groupValue = true;
	
	function render() {
		//是否有预定义好的checkbox
		$values = $this->attr("values");
		$labels = array();
		$options = array();
		if (!is_array($values)) {
			$options = $this->attr("options");
			if (is_array($options)) {
				$values = array_keys($options);
				$labels = array_values($options);
			}
		}
		$labels2 = $this->attr("labels");
		if (is_array($labels2)) {
			$labels = $labels2;
		}
		
		$checkboxes = array();
		if (is_array($values)) {
			$i = 0;
			foreach ($values as $key => $value) {
				$checkboxes[$key] = "<label><input type=\"checkbox\" value=\"" . $this->escape(strval($value)) . "\"";
				//name
				$name = null;
				if ($this->attr("name")) {
					$name = $this->escape($this->attr("name")) . "[]";
					$checkboxes[$key] .= " name=\"" . $name . "\"";
				}
				
				$selectValues = $this->attr("selected.values");
				$selectedList = $this->attr("selected.list");
				if ((is_array($selectValues) && in_array($value, $selectValues)) || ($selectedList && if_in_array($value, $selectedList)) || ($this->can("redisplay") && $name && !is_null($this->request($name)))) {
					$checkboxes[$key] .= " checked=\"checked\"";
				}
				$checkboxes[$key] .= "/>";
				if (isset($labels[$key])) {
					$checkboxes[$key] .= " " . $labels[$key];
				}
				$checkboxes[$key] .= "</label>";
			}
		}
		if (!empty($checkboxes)) {
			$checkboxes = implode($this->attr("separator"), $checkboxes);
		}
		else {
			$checkboxes = null;
		}
		
		return $checkboxes . "\${yield}" . $this->renderError();
	}
}

?>